package com.cmfi.service.impl.userRoleAuthImpl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cmfi.SpringbootApplication;
import com.cmfi.dao.userRoleAuthDao.MenuAuthDao;
import com.cmfi.dao.userRoleAuthDao.RoleDao;
import com.cmfi.dao.userRoleAuthDao.RoleMenuAuthDao;
import com.cmfi.domain.userRoleAuthEntity.MenuAuth;
import com.cmfi.domain.userRoleAuthEntity.Role;
import com.cmfi.domain.userRoleAuthEntity.RoleAndMenuAuth;
import com.cmfi.service.inter.userRoleAuthInter.RoleService;

@Service
public class RoleServiceImpl implements RoleService {
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private MenuAuthDao menuAuthDao;
	@Autowired
	private RoleMenuAuthDao roleMenuDao;
	
	static Logger logger = LoggerFactory.getLogger(SpringbootApplication.class);

	@Override
	public boolean saveRole(Role role) throws Exception {
		Role roleInDao = roleDao.getRoleByName(role.getRoleName());
		if (roleInDao != null) {
			throw new Exception("角色名已存在");
		}
		int result = roleDao.saveRole(role);
		return result > 0;
	}

	@Override
	public Role getRoleById(Long roleId) throws Exception {
		// TODO Auto-generated method stub
		return roleDao.getRoleById(roleId);
	}
	
	
	@Override
	public boolean authorizeMenuAuthForRole(Long permissionId, Long roleId) throws Exception {
		// TODO Auto-generated method stub
		MenuAuth permission = menuAuthDao.getMenuAuthById(permissionId);
		Role role = roleDao.getRoleById(roleId);
		if (permission == null) {
			throw new Exception("指定的权限不存在");
		}
		if (role == null) {
			throw new Exception("指定的角色不存在");
		}
		return roleMenuDao.saveUserRole(new RoleAndMenuAuth(roleId, permissionId)) > 0;
	}

	@Override
	public void delRole(Long roleId) throws Exception {
		// TODO Auto-generated method stub
		 roleDao.deleteById(roleId);
	}

	@Override
	public List<String> getAllRoles() {
		List<String> allRoles = new ArrayList<>();
		for (Role role : roleDao.getAllRoles()) {
			allRoles.add(role.getRoleName());
		}
		return allRoles;
	}
}
